package com.jimster.plugins.gadgets.scroller
{
	import com.greensock.TweenLite;
	import com.jimster.plugins.utils.MathUtil;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;

	public class ScrollerVertical extends ScrollerContent
	{
		//Variables
		private var mcContent:DisplayObject;
		private var mcScrub:MovieClip;
		private var mcScrubBar:MovieClip;
		private var numMaskHeight:Number;
		private var rootStage:Stage;
		private var numOffsetHeight:Number;
		
		//Constructor
		public function ScrollerVertical()
		{
			super();
		}
		
		//Public methods
		public function resetScroller():void
		{
			this.mcScrub.y = 0;
			this.mcContent.y = 0;
		}
		
		public function scrollToSpecificContentChild( $childY:Number ):void
		{
			var childPerPosition:Number = MathUtil.toPercentRatio( $childY, ( this.mcContent.height - this.numOffsetHeight ) );
			var scrubPos:Number = MathUtil.ratioToValue( childPerPosition, 0, this.mcScrubBar.height );
			TweenLite.to( this.mcScrub, .2, { y:scrubPos , onUpdate:this.onUpdateScrub } );
		}
		
		public override function updateContent($data:*):void
		{
			this.mcContent = null;
			this.mcContent = $data;
			super.updateContent( $data );
			
		}
		
		public override function initialize($data:ScrollerContentData):void
		{
			this.mcContent = $data.content;
			this.mcScrub = $data.scrub;
			this.mcScrubBar = $data.scrubBar;
			this.numMaskHeight = $data.maskHeight;
			this.rootStage = $data.rootStage;
			this.numOffsetHeight = $data.contentOffSetHeight;
			
			super.initialize( $data );
			this.createListeners();
		}
		
		//Private methods
		private function createListeners():void
		{
			this.mcScrub.buttonMode = true;
			this.mcScrub.addEventListener( MouseEvent.MOUSE_DOWN, this.onScrubDown );
			this.mcScrub.addEventListener( MouseEvent.MOUSE_UP, this.onScrubUp );
			if( this.rootStage != null )
			{
				this.rootStage.addEventListener( MouseEvent.MOUSE_UP, this.onScrubUp );
			}
		}
		
		//Event handlers
		private function onUpdateScrub( $event:Event=null ):void
		{
			var _numPercent:Number = MathUtil.toPercentRatio( this.mcScrub.y, this.mcScrubBar.height - this.mcScrub.height );
			var _numPosition:Number = MathUtil.ratioToValue( _numPercent, 0, ( this.mcContent.height + this.numOffsetHeight ) - this.numMaskHeight ) * -1;
			TweenLite.to( this.mcContent, .3, { y:_numPosition } );
		}
		
		private function onScrubUp( $event:MouseEvent ):void
		{
			this.mcScrub.stopDrag();
			this.removeEventListener( Event.ENTER_FRAME, this.onUpdateScrub );
		}
		
		private function onScrubDown( $event:MouseEvent ):void
		{
			this.mcScrub.startDrag( false, new Rectangle( 0, 0, 0, this.mcScrubBar.height - this.mcScrub.height ) );
			this.addEventListener( Event.ENTER_FRAME, this.onUpdateScrub );
		}
	}
}